package demo

import (
	"context"
	"fmt"
	"time"

	etcdclient "go.etcd.io/etcd/client/v3"
)

func init() {
	Register("EtcdLease", func() Service {
		return new(EtcdLease)
	})

	fmt.Println("EtcdLease registered")
}

type EtcdLease struct{}

func (el *EtcdLease) Exec() {
	client, err := etcdclient.New(etcdclient.Config{
		Endpoints:   []string{"http://localhost:2379"},
		DialTimeout: 5 * time.Second,
	})

	if err != nil {
		fmt.Printf("failed to etcd_lease: %v\n", err)
	}
	defer client.Close()

	// 创建一个5秒的租约
	resp, err := client.Grant(context.TODO(), 5)
	if err != nil {
		fmt.Printf("etcd grant failed, err:%v\n", err)
		return
	}

	// 5秒钟之后, /nazha/ 这个key就会被移除
	_, err = client.Put(context.TODO(), "/nazha/", "dsb", etcdclient.WithLease(resp.ID))
	if err != nil {
		fmt.Printf("etcd grant put failed, err:%v\n", err)
	}
}
